package com.qf.controller;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.qf.entity.User;
import com.qf.entity.base.ResultEntity;
import com.qf.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: xbb
 * @Date:2020/4/14
 */
@RestController
@RequestMapping("/res")
public class ResController {

    @Autowired
    private FastFileStorageClient ffsc;

    @Autowired
    private IUserService userService;

    @Value("${fastPath}")
    private String fastPath;

    @RequestMapping("/uploadFile")
    public ResultEntity uploadFile(Integer userId,MultipartFile file){
        //文件名
        String filename = file.getOriginalFilename();
        //文件的后缀
        String fileExName = filename.substring(filename.lastIndexOf(".")+1);
        try {
            //上传头像到fastdfs
            StorePath storePath = ffsc.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), fileExName, null);
            System.out.println(storePath.getFullPath());
            //获取小图的路径
            String minHead = fastPath+storePath.getFullPath().replace("."+fileExName, "_100x100."+fileExName);
            System.out.println(minHead);
            //获取大图的路径
            String maxHead = fastPath+storePath.getFullPath();
            System.out.println(maxHead);
            //修改用户表中的头像
            if(userId!=null){
                User user = userService.selectById(userId);
                user.setMaxHead(maxHead);
                user.setMinHead(minHead);
                userService.update(user);
            }
            Map<String,String> map = new HashMap<>();
            map.put("maxHead",maxHead);
            map.put("minHead",minHead);
            return ResultEntity.successs(map);  //resp.data.maxHead
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
